One-Time Pad (OTP)
Module 01 / Lesson 10
Visual Tutorial
The Concept of Perfect Secrecy
The One-Time Pad (OTP) is an encryption technique that cannot be cracked if used correctly. It was proven mathematically secure by Claude Shannon, meaning the ciphertext provides absolutely no information about the plaintext.
Three Strict Rules for OTP:
- True Randomness: The key must be generated using a truly random process.
- Key Length: The key must be at least as long as the message being encrypted.
- No Reuse: The key must be used only once and then destroyed.
Mathematical Representation
C = (P + K) mod 26
(Or using XOR logic for digital data)
Python Implementation
import secrets
def generate_otp_key(length):
# Using 'secrets' for cryptographically strong random numbers
return "".join(secrets.choice("ABCDEFGHIJKLMNOPQRSTUVWXYZ") for _ in range(length))
def otp_encrypt(plaintext, key):
ciphertext = ""
for p, k in zip(plaintext.upper(), key.upper()):
# (P + K) mod 26
c = chr(((ord(p) - 65) + (ord(k) - 65)) % 26 + 65)
ciphertext += c
return ciphertext
# Usage
msg = "SECRET"
key = generate_otp_key(len(msg))
print(f"Key: {key} \nCipher: {otp_encrypt(msg, key)}")